# -*- coding: utf-8 -*-
# @Author : yanhaopeng
# @Date   : 2019/12/18
# @File   : R37_EC_UpaidExternalGuaranteeBadAmtCheck_WHB_2D.py
# @E-mail : yanhaopeng95@163.com

'''eof
name:申请企业未结清对外担保业务余额校验（不良类）
code:R37_EC_UpaidExternalGuaranteeBadAmtCheck_WHB_2D
tableName:
columnName:
groups:弱规则>企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)



def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def factor1(data):
    '''
    factor1 = 相关还款责任汇总信息·借贷交易相关还款责任汇总信息段(EB05A)
               - 借贷交易相关还款责任汇总信息(EB05AH)·责任类型(EB05AD01) 
               ∈(1(个人信贷交易共同还款人/共同债务人)，2(担保人)，9(其他))
               ·count(其他借贷交易账户不良类余额(EB05AJ06)>0)
    '''

    EBE = getTable(data, 'EBE', 1)
    if EBE is None:
        return None
    elif EBE == [{}] or EBE == "":
        return 0
    else:
        #相关还款责任汇总信息单元  [0..1]
        EB05 = getTable(EBE[0], 'EB05', 0)
        if EB05 is None:
            return None
        elif EB05 == [{}] or EB05 == "":
            return 0
        else:
            #借贷交易相关还款责任汇总信息段  [0..1]
            EB05A = getTable(EB05[0], 'EB05A', 0)
            if EB05A is None or EB05A == "":
                return None
            elif EB05A == [{}]:
                return 0
            else:
                #借贷交易相关还款责任汇总信息   [0..4]
                EB05AH = getTable(EB05A[0], 'EB05AH', 0)
                if EB05AH is None or EB05AH == "":
                    return None
                elif EB05AH == [{}]:
                    return 0
                else:
                    result = []
                    for i in EB05AH:
                        try:
                            #责任类型
                            EB05AD01 = i.get('EB05AD01')
                            #其他借贷交易账户不良类余额
                            EB05AJ06 = i.get('EB05AJ06')
                            if EB05AD01 in null_type_list or EB05AJ06 in null_type_list:
                                result.append(None)
                            elif EB05AD01 in ['1','2','9'] and isfloat(EB05AJ06) and float(EB05AJ06) > 0:
                                #1-个人信贷交易共同还款人/共同债务人，2-保证人，9-其他
                                result.append(1)
                            else:
                                result.append(0)
                        except:
                            result.append(None)
                            continue 
                    result = filter(lambda x: x is not None, result)
                    if len(result) == 0:
                        return None
                    else:
                        return sum(result)


def factor2(data):
    '''
    factor2 = 相关还款责任汇总信息·担保交易相关还款责任汇总信息段(EB05B)
                ·责任类型(EB05BD01)∈(1(个人信贷交易共同还款人),2(反担保人),9(其他),0(合计))
                ·count(不良类余额(EB05BJ04)>0)
    '''
    EBE = getTable(data, 'EBE', 1)
    if EBE is None:
        return None
    elif EBE == [{}] or  EBE == "":
        return 0
    else:
        #相关还款责任汇总信息单元  [0..1]
        EB05 = getTable(EBE[0], 'EB05', 0)
        if EB05 is None:
            return None
        elif EB05 == [{}] or EB05 == "":
            return 0
        else:
            #担保交易相关还款责任汇总信息段   [0..1]
            EB05B = getTable(EB05[0], 'EB05B', 0)
            if EB05B is None or EB05B == "":
                return None
            elif EB05B ==[{}]:
                return 0
            else:
                #担保交易相关还款责任汇总信息   [0..4]
                EB05BH = getTable(EB05B[0], 'EB05BH', 0)
                if EB05BH is None or EB05BH == "":
                    return None
                elif EB05BH ==[{}]:
                    return 0
                else:
                    result = []
                    for i in EB05BH:
                        try:
                            #责任类型
                            EB05BD01 = i.get('EB05BD01')
                            #不良余额
                            EB05BJ04 = i.get('EB05BJ04')
                            if EB05BD01 in null_type_list or EB05BJ04 in null_type_list:
                                result.append(None)
                            elif EB05BD01 in ['1','2','9','0'] and isfloat(EB05BJ04) and float(EB05BJ04) > 0:
                                # 1-个人担保交易的共同债务人，2-反担保人，9-其他，0-合计
                                result.append(1)
                            else:
                                result.append(0)
                        except:
                            result.append(None)
                            continue
                    result = filter(lambda x: x is not None, result)
                    if len(result) == 0:
                        return None
                    else:
                        return sum(result)

def factor3(data):
    '''
    factor3 = 统计符合相关还款责任借贷账户(不含贴现)信息单元(ED07)
    ·主借款人身份识别(ED070D01)∈(1(自然人),2(组织机构), and
    相关还款责任类型(ED070D03)∈(1(个人信贷交易共同还款人),2(保证人),
    3(票据承兑人),4(应收账款债务人),5(供应链核心企业),9(其他)and
    五级分类(ED070D08)∈(3(次级),4(可疑),5(损失),6(违约)的笔数
    '''
    #相关还款责任信息   [1..1]
    EDD = getTable(data, 'EDD', 1)
    if EDD is None:
        return None
    elif EDD == [{}] or EDD == "":
        return 0
    else:
        #相关还款责任借贷账户（不含贴现）信息单元   [0..*]
        ED07 = getTable(EDD[0], 'ED07', 0)
        if ED07 is None or ED07 == "":
            return None
        elif ED07 == [{}]:
            return 0
        else:
            result = []
            for i in ED07:
                try:
                    #主借款人身份类别
                    ED070D01 = i.get('ED070D01')
                    #相关还款责任人类型
                    ED070D03 = i.get('ED070D03')
                    #五级分类
                    ED070D08 = i.get('ED070D08')
                    #条件list
                    #1-自然人，2-组织机构
                    ED070D01_list = ['1','2']
                    #1-个人信贷交易共同还款人，2-保证人，3-票据承兑人，4-应收账款债务人，5-供应链核心企业，9-其他
                    ED070D03_list = ['1','2','3','4','5','9']
                    #3-次级，4-可疑，5-损失，6-违约
                    ED070D08_list = ['3','4','5','6']

                    if ED070D01 in null_type_list or ED070D03 in null_type_list or ED070D08 in null_type_list:
                        result.append(None)
                    elif ED070D01 in ED070D01_list and ED070D03 in ED070D03_list and ED070D08 in ED070D08_list:
                        result.append(1)
                    else:
                        result.append(0)
                except:
                    result.append(None)
                    continue
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)

def factor4(data):
    '''
    factor4 = 统计相关还款责任担保账户分机构汇总信息单元(ED09)·相关还款责任类型(ED070D03)
            ∈(1,(个人担保交易的共同债务人)，2(反担保人)，9(其他)) and 
            五级分类(ED090D04)∈(3(次级),4(可疑),5(损失),6(违约)的笔数
    '''
    #相关还款责任信息   [1..1]
    EDD = getTable(data, 'EDD', 1)
    if EDD is None:
        return None
    elif EDD == [{}] or EDD == "":
        return 0
    else:
        #相关还款责任担保账户分机构汇总信息单元   [0..*]
        ED09 = getTable(EDD[0], "ED09", 0)
        if ED09 is None or ED09 == "":
            return None
        elif ED09 == [{}]:
            return 0
        else:
            result = []
            for i in ED09:
                try:
                    #相关还款责任类型
                    ED090D01 = i.get('ED090D01')
                    #五级分类
                    ED090D04 = i.get('ED090D04')
                    #条件list
                    #1-个人担保交易的共同债务人，2-反担保人，9-其他
                    ED090D01_list = ['1','2','9']
                    #3-次级，4-可疑，5-损失，6-违约
                    ED090D04_list = ['3','4','5','6']
                    if ED090D01 in null_type_list or ED090D04 in null_type_list:
                        result.append(None)
                    elif ED090D01 in ED090D01_list and ED090D04 in ED090D04_list:
                        result.append(1)
                    else:
                        result.append(0)
                except:
                    result.append(None)
                    continue
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return None
            else:
                return sum(result)


def R37_EC_UpaidExternalGuaranteeBadAmtCheck_WHB_2D():
    data = EC_DSJ_2D['data']

    f1 = factor1(data)
    f2 = factor2(data)
    f3 = factor3(data)
    f4 = factor4(data)


    if f1 is None and f2 is None and f3 is None and f4 is None:
        return u'缺失值'
    else: 
        if f1 is None:
            f1 = 0
        if f2 is None:
            f2 = 0
        if f3 is None:
            f1 = 0
        if f4 is None:
            f1 = 0
        factor = max(f1, f2, f3, f4)
        return factor


result = R37_EC_UpaidExternalGuaranteeBadAmtCheck_WHB_2D()

if __name__ == '__main__':

    import json
    
    with open('./EC_DSJ1.json', 'r') as f:
        EC_DSJ = json.loads(f.read())['EC_DSJ']
    print R37_EC_UpaidExternalGuaranteeBadAmtCheck_WHB_2D()